package com.rr.graphql.config;

import com.netflix.graphql.dgs.client.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * @author RR
 * @date 2023/7/9 15:05
 */
@Configuration
public class ClientConfig {
    private static final String GRAPH_QL_URL = "http://localhost:8080/graphql";
    @Bean
    public CustomGraphQLClient customGraphQLClient(){
        CustomGraphQLClient client = GraphQLClient.createCustom(GRAPH_QL_URL,  (url, headers, body) -> {
            HttpHeaders httpHeaders = new HttpHeaders();
            headers.forEach(httpHeaders::addAll);
            ResponseEntity<String> exchange = new RestTemplate().exchange(url, HttpMethod.POST, new HttpEntity<>(body, httpHeaders),String.class);
            return new HttpResponse(exchange.getStatusCodeValue(), exchange.getBody());
        });
        return client;
    }
}
